package com.ky.tms.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ky.tms.entity.TmsCost;
import com.ky.tms.entity.TmsOrder;
import com.ky.tms.exception.PredictableException;
import com.ky.tms.mapper.TmsCostMapper;
import com.ky.tms.mapper.TmsOrderMapper;
import com.ky.tms.service.ITmsReportService;
import com.ky.tms.vo.CostExportVo;
import com.ky.tms.vo.OrderExportVo;
import com.ky.tms.vo.OrderIncomeAudit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.List;

@Service
public class TmsReportServiceImpl implements ITmsReportService {

    @Autowired
    private TmsOrderMapper tmsOrderMapper;

    @Autowired
    private TmsCostMapper tmsCostMapper;

    @Override
    public IPage<OrderIncomeAudit> reportOrderPage(String userNam, TmsOrder tmsOrder, Long limit, Long pages) {
        IPage<OrderIncomeAudit> page = new Page(pages, limit);
        List<OrderIncomeAudit> tmsOrders = tmsOrderMapper.incomeAuditPage(page, tmsOrder);
        for(OrderIncomeAudit order : tmsOrders){
            List<OrderIncomeAudit> orderChildren = tmsOrderMapper.reportOrderPage(order.getId());
            if(orderChildren.size() > 0){
                order.setChildren(orderChildren);
            }
        }
        page.setRecords(tmsOrders);
        return page;
    }

    @Override
    public List<OrderIncomeAudit> incomeBar(TmsOrder order) {
        return tmsOrderMapper.incomeBar(order);
    }

    @Override
    public void entryOrderTemplate(HttpServletResponse response) throws PredictableException {
        OutputStream outputStream = null;
        InputStream inputStream = null;
        BufferedInputStream bis = null;
        byte[] buffer = new byte[1024];
        try{
            ClassPathResource resource = new ClassPathResource("excelTemplate" + File.separator + "entryOrder.xlsx");
            inputStream = resource.getInputStream();
            outputStream = response.getOutputStream();
            response.setContentType("application/octet-stream");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("新建订单导入模板", "UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
            bis = new BufferedInputStream(inputStream);
            int i = -1;
            while ((i = bis.read(buffer))>0){
                outputStream.write(buffer, 0, i);
            }
        }catch (Exception e){
            e.printStackTrace();
            throw new PredictableException("下载失败");
        } finally {
            if(outputStream != null){
                try{
                    outputStream.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
            if(bis != null){
                try{
                    bis.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
            if(inputStream != null){
                try{
                    inputStream.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
            System.gc();
        }
    }

    @Override
    public void orderExport(TmsOrder tmsOrder, HttpServletResponse response) throws PredictableException {
        try{
            List<OrderExportVo> orderExportVos = tmsOrderMapper.exportOrder(tmsOrder);
            // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("订单报表", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), OrderExportVo.class).sheet("订单报表").doWrite(orderExportVos);
        }catch (Exception e){
            e.printStackTrace();
            throw new PredictableException("导出失败！");
        }


    }

    @Override
    public void costExport(TmsCost tmsCost, HttpServletResponse response) throws PredictableException {
        try{
            List<CostExportVo> costExportVos = tmsCostMapper.costExport(tmsCost);
            // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("费用报表", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), CostExportVo.class).sheet("费用报表").doWrite(costExportVos);
        }catch (Exception e){
            e.printStackTrace();
            throw new PredictableException("导出失败！");
        }
    }
}
